#include "Stdafx.h"
#include "SceneManager.h"

namespace Pulpy
{
	Scene * SceneManager::_CurrentScene = NULL;
	Scene * SceneManager::_PreviousScene = NULL;
	Scene * SceneManager::_OverlayScene = NULL;
	std::map<std::string, Scene *> SceneManager::_SceneList;

	void SceneManager::changeScene(std::string name)
	{
		if(_CurrentScene != NULL && _CurrentScene !=  _SceneList[name])
		{
			//Previous Previous Scene is cleared and freeing up resources
			if(_PreviousScene != NULL)
			{
				_PreviousScene->reset();
				_PreviousScene->freeResource();
				
				_PreviousScene->toggleReady();
			}
			_PreviousScene = _CurrentScene;
		}
		_CurrentScene = _SceneList[name];
		if(_CurrentScene->isReady() == false)
		{
			_CurrentScene->loadResource();
			_CurrentScene->toggleReady();
		}
	}
	void SceneManager::clearOverlayScene()
	{
		if(_OverlayScene != NULL)
		{
			_OverlayScene->reset();
			_OverlayScene->freeResource();
			_OverlayScene->toggleReady();
			_OverlayScene = NULL;
		}
	}

	void SceneManager::setOverlayScene(std::string name)
	{
		_OverlayScene = _SceneList[name];
		if(_OverlayScene->isReady() == false)
		{
			_OverlayScene->loadResource();
			_OverlayScene->toggleReady();
		}
	}
	void SceneManager::handleMouseMove(int x, int y)
	{
		if(_OverlayScene == NULL && _CurrentScene != NULL)
			_CurrentScene->handleMouseMove(x, y);
		else if(_OverlayScene != NULL)
			_OverlayScene->handleMouseMove(x, y);
	}

	void SceneManager::drawScenes()
	{
		if(_CurrentScene != NULL)
		{
			glColor4f(1,1,1,1);
			_CurrentScene->draw();
		}
		if(_OverlayScene != NULL)
		{
			glColor4f(1,1,1,0.75);
			_OverlayScene->draw();
		}
	}
	void SceneManager::updateScenes()
	{
		if(_OverlayScene == NULL && _CurrentScene != NULL)
			_CurrentScene->update();
		else if(_OverlayScene != NULL)
			_OverlayScene->update();
	}
	void SceneManager::handleKeyboard(int key, int x, int y)
	{
		if(_OverlayScene == NULL && _CurrentScene != NULL)
			_CurrentScene->handleKeyboard(key, x, y);
		else if(_OverlayScene != NULL)
			_OverlayScene->handleKeyboard(key, x, y);
	}
	void SceneManager::handleKeyboardUp(int key, int x, int y)
	{
		if(_OverlayScene == NULL && _CurrentScene != NULL)
			_CurrentScene->handleKeyboardUp(key, x, y);
		else if(_OverlayScene != NULL)
			_OverlayScene->handleKeyboardUp(key, x, y);
	}
	void SceneManager::handleKeyboardSpecial(int key, int x, int y)
	{
		if(_OverlayScene == NULL && _CurrentScene != NULL)
			_CurrentScene->handleKeyboardSpecial(key, x, y);
		else if(_OverlayScene != NULL)
			_OverlayScene->handleKeyboardSpecial(key, x, y);
	}
	void SceneManager::handleMouseClick(int button, int state, int x, int y)
	{
		if(_OverlayScene == NULL && _CurrentScene != NULL)
			_CurrentScene->handleMouseClick(button,state, x, y);
		else if(_OverlayScene != NULL)
			_OverlayScene->handleMouseClick(button,state, x, y);
	}
}